package org.sanm.domain.file;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.util.IOUtils;

import org.sanm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


/**
 * @author zhengm
 */
@Service
public class FileService {


    @Value("${ecloud.end.point}")
    private String eCloudEndPoint;
    @Value("${ecloud.access.url}")
    private String eCloudAccessUrl;
    @Value("${ecloud.region}")
    private String eCloudRegion;
    @Value("${ecloud.access.key}")
    private String eCloudAccessKey;
    @Value("${ecloud.secret.key}")
    private String eCloudSecretKey;
    @Value("${ecloud.bucket.name}")
    private String eCloudBucketName;
    @Value("${ecloud.bucket.env}")
    private String ecloudBucketEnv;

    public String uploadFile(MultipartFile file) throws Exception {

        String result = "";
        // 创建 AmazonS3 实例。
        AmazonS3 client = getAmazonS3Client();
        // 分块上传对象流
        TransferManager tm = TransferManagerBuilder.standard().withS3Client(client).build();
        try {

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = now.format(formatter);

            String objectName = ecloudBucketEnv + "/" + formattedDate + "/" + RandomUtil.genUuid() + "-" + file.getOriginalFilename();
            // 设置对象（Object）大小，如果不设置，由于数据会全部缓存在内存中，可能会将内存耗尽。
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(file.getSize());
            InputStream inputStream = file.getInputStream();
            try {
                PutObjectRequest putObjectRequest = new PutObjectRequest(eCloudBucketName, objectName, inputStream, meta);
                putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
                // TransferManager 采用异步方式进行处理，因此该调用会立即返回。
                Upload upload = tm.upload(putObjectRequest);
                // 等待上传全部完成。
                upload.waitForCompletion();
                // https://zher-b.eos.fujian-3.cmecloud.cn/test/1-1-81d19ce5b17a475cbe340d28958c2da4-hcfl.jpg
                result = eCloudAccessUrl + objectName;
            } catch (Exception e) {
                throw e;
            } finally {
                IOUtils.closeQuietly(inputStream, null);
            }

            return result;
        } finally {
            // 在完成操作后，必须显示关闭 TransferManager。
            tm.shutdownNow();
            // 关闭 client。
            client.shutdown();
        }
    }


    private AmazonS3 getAmazonS3Client() {
        // 创建 AmazonS3 实例。
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(eCloudEndPoint, eCloudRegion);
        BasicAWSCredentials credentials = new BasicAWSCredentials(eCloudAccessKey, eCloudSecretKey);
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        return AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(endpointConfiguration)
                .withCredentials(credentialsProvider).build();
    }


//    public String downFileBase64(String objectName) throws IOException {
//        // 创建 AmazonS3 实例。
//        AmazonS3 client = getAmazonS3Client();
//
//        S3Object s3Object = client.getObject(eCloudBucketName, objectName);
//        try (InputStream inputStream = s3Object.getObjectContent()) {
//            // 转字节数组
//            byte[] bytes = IOUtils.toByteArray(inputStream);
//            // 大于等于2M, 压缩
//            long fileSize = 1024 * 1024 * 2;
//            return Base64Util.zipOrNotImage(bytes, fileSize);
//        } catch (Exception e) {
//            throw e;
//        } finally {
//            // 关闭 client。
//            client.shutdown();
//        }
//    }


}
